<template>
  <div style="height:100%;">
    <div v-if="!$store.getters.isEmpty">
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <div style="min-height:200px;">
          <van-card
            v-for="item in carList"
            :key="item.id"
            :num="item.count"
            :price="item.sell_price"
            :title="item.title"
            :thumb="item.thumb_path"
          >
            <div slot="footer">
              <van-stepper @plus="add(item.id)" @minus="sub(item.id)" v-model="item.count" />
            </div>
          </van-card>
        </div>
      </van-pull-refresh>
    </div>
    <div v-else class="empty">
      <img src="../assets/cart_empty.png" alt />
      <p>购物车空空如也</p>
      <van-button @click="goGoodsList" type="info" size="mini">去逛逛</van-button>
    </div>
    <van-submit-bar :price="total" button-text="提交订单" @submit="onSubmit" />
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      carList: [],
      loading: false,
      finished: false,
      isLoading: true
    };
  },
  methods: {
    ...mapMutations(["add", "sub"]),
    onSubmit() {},
    async getCarList(cb) {
      let arr = [];
      console.log(this.carArr);
      if (this.carArr.length == 0) return;
      this.carArr.forEach(item => {
        arr.push(item.id);
      });
      console.log(arr);
      let ids = arr.toString();
      const { data: res } = await this.$http(
        "/api/goods/getshopcarlist/" + ids
      );
      if (res.status != 0) return this.$toast("请求服务器失败");
      let temp = JSON.parse(localStorage.getItem("car"));
      temp.forEach(item1 => {
        res.message.forEach(item2 => {
          if (item1.id == item2.id) {
            item2.count = item1.count;
          }
        });
      });
      cb && cb();
      this.carList = res.message;
    },
    goGoodsList() {
      this.$router.push("/goods/list");
    },
    onRefresh() {
      this.getCarList(() => {
        this.$toast("刷新成功");
        this.isLoading = false;
      });
    }
  },
  created() {
    this.getCarList();
  },
  computed: {
    ...mapState(["carArr"]),
    total() {
      let total = 0;
      this.carArr.forEach(item => {
        console.log(item.count);
        console.log(item.price);
        total += item.count * item.price * 100;
      });
      return total;
    }
  }
};
</script>

<style lang='less' scoped>
.van-submit-bar {
  bottom: 0px;
  position: fixed;
}
.van-card {
  margin: 10px 0;
}
.empty {
  color: #ccc;
  padding: 15px 0;
  img {
    width: 100px;
  }
  text-align: center;
}
</style>